package com.lehecai.core.search.api.impl.parser;

import com.lehecai.core.search.api.ISearchApiResponseBody;
import com.lehecai.core.search.api.SearchApiConstant;
import com.lehecai.core.search.api.impl.AggregateSearchApiResponseBody;
import com.lehecai.core.util.CoreJSONUtils;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class AggregateSearchApiResponseBodyParser extends AbstractSearchApiResponseBodyParser {

    @Override
    public ISearchApiResponseBody parse(JSON bodyJSON) throws Exception {

        JSONObject resultObject = (JSONObject)bodyJSON;
        int total = CoreJSONUtils.getInt(resultObject, SearchApiConstant.API_RETURN_BODY_TOTAL);

        JSONArray resultArray = CoreJSONUtils.getArray(resultObject, SearchApiConstant.API_RETURN_BODY_VALUE);

        List<JSONArray> resultList = new ArrayList<JSONArray>();

        if (resultArray != null && !resultArray.isEmpty()) {
            for (int i = 0; i < resultArray.size(); i++) {
                JSONArray jsonArray = resultArray.getJSONArray(i);
                resultList.add(jsonArray);
            }
        }

        return new AggregateSearchApiResponseBody(resultList, total);
    }
}